package com.qdlc.p2p.biz.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.alibaba.fastjson.JSON;
import com.qdlc.p2p.biz.service.TokenStoreService;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.dto.TokenStore;

/**
 * App Token过滤器
 * @author wj1x
 * @version 2.0
 * @date 2015年8月9日 上午10:06:01
 */
public class AppTokenFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String oauthToken = request.getParameter("oauthToken");
		String refreshToken = request.getParameter("refreshToken");
		TokenStoreService tokenStoreService = (TokenStoreService)BeanUtil.getBean("tokenStoreService");
		TokenStore tokenStore =new TokenStore();
		if(StringUtil.isBlank(oauthToken)){//token不存在
			if(StringUtil.isBlank(refreshToken)){//刷新令牌
				Map<String, Object> data = new HashMap<String, Object>();
	    		data.put("resCode", "4");
				data.put("resMsg", "token不能为空!");
	    		response.setContentType("application/json;charset=UTF-8");
	    		PrintWriter out = response.getWriter();
	    		out.print(JSON.toJSONString(data));
	    		out.flush();
	    		out.close();
			}else{
				chain.doFilter(request, response);
			}
		}else{
			tokenStore = tokenStoreService.getTokenByOauthToken(oauthToken);
			if(StringUtil.isBlank(tokenStore)){
				Map<String, Object> data = new HashMap<String, Object>();
	    		data.put("resCode", "3");
				data.put("resMsg", "token不存在！");
	    		response.setContentType("application/json;charset=UTF-8");
	    		PrintWriter out = response.getWriter();
	    		out.print(JSON.toJSONString(data));
	    		out.flush();
	    		out.close();
			}else{
				long addTime =  tokenStore.getAddTime().getTime();
				long validTime = Long.valueOf(System.currentTimeMillis())-addTime;			//差值
				long expireIn = Long.valueOf(tokenStore.getExpiresIn())*60*60*60*1000;		//有效时间
				if(expireIn < validTime){
					Map<String, Object> data = new HashMap<String, Object>();
		    		data.put("resCode", "3");
					data.put("resMsg", "token过期！");
		    		response.setContentType("application/json;charset=UTF-8");
		    		PrintWriter out = response.getWriter();
		    		out.print(JSON.toJSONString(data));
		    		out.flush();
		    		out.close();
				}else{
					chain.doFilter(request, response);
				}
			}
			
		}
		
	}

	public void init(FilterConfig fConfig) throws ServletException {
		
	}

	public AppTokenFilter() {
		
	}

	public void destroy() {

	}

}


